﻿using System;
using System.Collections.Generic;
using System.Text;
using FluorineFx;
using FluorineFx.AMF3;
using FluorineFx.Data;
using FluorineFx.Context;
using MySql.Data.MySqlClient;
using Could.Service.Utilitis;

namespace Could.Service
{
    [FluorineFx.RemotingService("Web Could ServiceLibrary")]
    public class ServiceLib
    {
        private string pAdminEmail = "eulersin@gmail.com";
        public ServiceLib(){}
        public string Echo(string s){
            FluorineContext.Current.Session["KK"] += "1";
            return "Echo:" + FluorineContext.Current.Session["KK"];
        }

        public Boolean ChangePasswd( string lostKey, string pwd){
            //string svalue = BaseData.GetUserData(userid, "user_email");
            Boolean bRet;
            pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
            string user_id = BaseData.GetUserData("user_id", "cat_user_lostkey", "lostkey", lostKey);
            string sql = "UPDATE sphinx_cat.tmscreators SET  user_pw = @user_pw	WHERE user_id= @user_id";
            MySqlConnection connection = new MySqlConnection(BaseData.GetConnectionString());
            try
            {
                MySqlCommand command = new MySqlCommand(sql, connection);
                connection.Open();
                command.Parameters.AddWithValue("@user_pw", pwd);
                command.Parameters.AddWithValue("@user_id", user_id);
                bRet = command.ExecuteNonQuery() > 0;
                if (bRet)
                {
                    sql = "DELETE FROM  sphinx_cat.cat_user_lostkey WHERE lostkey ='" + lostKey + "'";
                    command = new MySqlCommand(sql, connection);
                    command.ExecuteNonQuery();
                }
            }
            catch (System.Exception){
                return false;
            }
            return bRet;
        }

        public  string sendmail( string userid)
        {
            string svalue = BaseData.GetUserData(userid, "user_email");
            string href = GetUserLostKey(userid);
            Cemail mail = new Cemail();
            mail.pstrFrom = pAdminEmail;
            mail.pstrTo = svalue;
            mail.Body = mail.GetBody(userid, href);
            Boolean bvalue =  mail.SendSMTPEmail();
            if (bvalue){
                int i = svalue.IndexOf("@");
                svalue = "******" + svalue.Substring(i);
                return svalue;
            }else{
                return "";
            }
        }

        private string GetUserLostKey( string userid){
            
            string sLostKey = BaseData.GetUserData("lostkey", "cat_user_lostkey", "user_id", userid);
            if (sLostKey.Length > 0) return sLostKey;
            else{
                MySqlConnection connection = new MySqlConnection(BaseData.GetConnectionString());
                try
                {
                    sLostKey = DateTime.Now.Ticks.ToString();
                    string sql = "INSERT INTO sphinx_cat.cat_user_lostkey(user_id, lostkey) VALUES(@user_id,@lostkey)";
                    MySqlCommand command = new MySqlCommand(sql, connection);
                    connection.Open();
                    command.Parameters.AddWithValue("@user_id", userid);
                    command.Parameters.AddWithValue("@lostkey", sLostKey);
                    command.ExecuteNonQuery();
                }
                catch (System.Exception)
                {
                	sLostKey = "";
                }
            }
            return sLostKey;
        }


        public ASObject GetDataObject( string word) {
            LexiconForm lf = new LexiconForm();
            ASObject aso = new ASObject(); 
            try
            {
                aso["id"] = 1;
                aso["XMLData"] = 2;
            }
            catch (System.Exception )
            {
                throw new DataSyncException(lf, null);
            }

            return aso;
        }
        public LexiconForm GetLexicon( string word ){
            LexiconForm lf = new LexiconForm();
            lf.Word = word;
            lf.Relation = "dictionary, Dictionaries";
            lf.Sentence = "to consult a dictionary ";
            lf.XMLContext = "<b>IEEE標準詞彙權威字典第七版Authoritative Dictionary of IEEE Standards Terms </b>";
            lf.Voice = " [zi dian]";
            return lf;
        }
 
        public Cattmscreators RegisterUser(Cattmscreators obj)
        {
           
            MySqlConnection connection = new MySqlConnection(BaseData.GetConnectionString());
            try
            {
                string sql = "SELECT id,value FROM cat_sys_basedata WHERE ID=12";
                MySqlCommand command = new MySqlCommand(sql, connection);
                connection.Open();
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while(reader.Read()){
                        obj.XMLData = reader.GetString("value");
                    }
                }

                sql = "INSERT INTO sphinx_cat.tmscreators (user_machineid, user_id, user_email, user_pw, XMLData, online,last_login_time,yaoqingma) " +
                      "VALUES(@user_machineid, @user_id, @user_email,@user_pw,@XMLData,@online,@last_login_time,@yaoqingma)";
                command = new MySqlCommand(sql, connection);
                command.Parameters.AddWithValue("@user_machineid", obj.user_machineid);
                command.Parameters.AddWithValue("@user_id", obj.user_id);
                command.Parameters.AddWithValue("@user_email", obj.user_email);
                command.Parameters.AddWithValue("@user_pw", obj.user_pw);
                command.Parameters.AddWithValue("@XMLData", obj.XMLData);
                command.Parameters.AddWithValue("@online", obj.online);
                command.Parameters.AddWithValue("@last_login_time", DateTime.Now);
                command.Parameters.AddWithValue("@yaoqingma", obj.yaoqingma);
                command.ExecuteNonQuery();

                sql = "SELECT LAST_INSERT_ID()";
                command = new MySqlCommand(sql, connection);
                obj.ID = Convert.ToInt32( command.ExecuteScalar() );
            }
            catch (System.Exception )
            {
            	 throw new Exception("Incorrect code, please try again");
            }
            return obj;
        }

        public Cattmscreators Logsys( Cattmscreators obj){
            string user_pw = BaseData.GetUserData(obj.user_id, "user_pw").ToUpper();
            if (user_pw == null || user_pw.Length==0){
                obj.error = "ERR:不存在这个译员帐号";
            }else  if ( user_pw.Equals( obj.user_pw )) {
                obj.ID = Convert.ToInt32( BaseData.GetUserData(obj.user_id , "ID") );
                obj.user_machineid = BaseData.GetUserData(obj.user_id, "user_machineid");
                obj.user_email = BaseData.GetUserData(obj.user_id, "user_email");
                obj.XMLData = BaseData.GetUserData(obj.user_id, "XMLData");
                obj.online = true;
                obj.last_login_time = DateTime.Now.ToString();
                obj.yaoqingma = BaseData.GetUserData(obj.user_id, "yaoqingma");
                obj.error = "";
                obj.columns = BaseData.GetSysBaseData(18);
                obj.enginelist = GetEnginx();
            }else{
                obj.error = "Err:帐号密码错误！";
            }

            return obj;
        }

        public Boolean SelectFile( Cattmscreators obj){
            return BaseData.SetUserData(obj.ID, "XMLData" , obj.XMLData);
        }

        private System.Collections.ArrayList GetEnginx() {
            System.Collections.ArrayList arrlist= new System.Collections.ArrayList();
            MySqlConnection connection = new MySqlConnection(BaseData.GetConnectionString());
            try
            {
                string sql = "SELECT id,name, zhcn,indexField,textField FROM sphinx_cat.tmsenginx WHERE enabled=1 ORDER BY sort";
                MySqlCommand command = new MySqlCommand(sql, connection);
                connection.Open();
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        ASObject aso = new ASObject();
                        aso["data"] = reader.GetString("id");
                        aso["name"] = reader.GetString("name");
                        aso["label"] = reader.GetString("zhcn");
                        aso["indextmsField"] = "otxt"; //reader.GetString("indexField");
                        aso["texttmsField"] = "ttxt";// reader.GetString("textField");
                        aso["indextdbField"] = "oterm";
                        aso["texttdbField"] = "tterm";
                        arrlist.Add( aso );
                    }
                }
            }
            catch (System.Exception) { }
            return arrlist;
        }

        public Boolean Check_UserID( Cattmscreators obj){
            MySqlConnection connection = new MySqlConnection(BaseData.GetConnectionString());
            try
            {
                string sql = "SELECT count(id) FROM sphinx_cat.tmscreators WHERE user_id='" + obj.user_id.Trim() + "'";
                MySqlCommand command = new MySqlCommand(sql, connection);
                int r = Convert.ToInt32(command.ExecuteScalar());
                return r == 0; 
            }
            catch (System.Exception){}
            return false;
        }

        //public void setBaseDatasFromid(int id, string data, string title)
        //{
        //    MySqlConnection conn = new MySqlConnection();
            
        //    using (OleDbConnection connection = new OleDbConnection(FoodsDAO.ConnectionString))
        //    {
        //        connection.Open();
        //        OleDbCommand command = new OleDbCommand(null, connection);
        //        command.CommandText = @"UPDATE BaseDatas SET XMLData = ?, Title=? WHERE ID= ?";
        //        command.Parameters.Add(new System.Data.OleDb.OleDbParameter("XMLData", System.Data.OleDb.OleDbType.VarWChar, 5000, "XMLData")).Value = data;
        //        command.Parameters.Add(new System.Data.OleDb.OleDbParameter("Title", System.Data.OleDb.OleDbType.VarWChar, 50, "Title")).Value = (title == null ? DBNull.Value : (object)title);
        //        command.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ID", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ID", System.Data.DataRowVersion.Original, null)).Value = id;

        //        int rowsAffected = command.ExecuteNonQuery();
        //        if (rowsAffected == 0)
        //            throw new Exception("Row = 0");
        //    }
        //}
        //public ASObject getBaseDatasFromTitle(string sTitle)
        //{
        //    using (OleDbConnection connection = new OleDbConnection(FoodsDAO.ConnectionString))
        //    {
        //        ASObject aso = new ASObject();
        //        string query = "SELECT * FROM [BaseDatas] WHERE title ='" + sTitle + "'";
        //        OleDbCommand command = new OleDbCommand(query, connection);
        //        connection.Open();
        //        using (OleDbDataReader reader = command.ExecuteReader())
        //        {
        //            while (reader.Read())
        //            {
        //                aso["id"] = reader.GetInt32(reader.GetOrdinal("ID"));
        //                aso["Title"] = reader.GetValue(reader.GetOrdinal("Title")).ToString();
        //                aso["XMLData"] = reader.GetValue(reader.GetOrdinal("XMLData")).ToString();
        //                aso["help"] = reader.GetValue(reader.GetOrdinal("help")).ToString();
        //            }
        //        }

        //        return aso;
        //    }
        //}
        //private void Validate(string data)
        //{
        //    StringBuilder errors = new StringBuilder();

        //    if (data == null || data.Equals(""))
        //    {
        //        errors.Append("数据不能为空!!!");
        //    }
        //    if (errors.Length > 0)
        //        throw new NoNullAllowedException(errors.ToString());
        //}
    }
}
